﻿using FlyingEye.Consts;
using FlyingEye.Models;
using FlyingEye.Models.EncryptionMachineResults;
using FlyingEye.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using Volo.Abp.AspNetCore.Mvc;

namespace FlyingEye.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class EncryptionMachineController : AbpController
    {
        private readonly EncryptionMachineService _service;

        private readonly ILogger<EncryptionMachineController> _logger;

        public EncryptionMachineController(EncryptionMachineService service,
            ILogger<EncryptionMachineController> logger)
        {
            _service = service;
            _logger = logger;
        }

        /// <summary>
        /// 将明文加密成密文数据。
        /// </summary>
        /// <param name="model">加密model</param>
        /// <returns>返回操作结果，以及加密后的密文</returns>
        [HttpPost]
        public async Task<ActionResult<EncryptionMachineEncryptResult>> Encrypt(EncryptionMachineEncryptedModel model)
        {
            var result = new EncryptionMachineEncryptResult();

            try
            {
                var encryptedBase64String = await _service.EncryptAsync(model);
                result.IsSuccess = true;
                result.EncryptedValue = encryptedBase64String;
                result.Message = EncryptionMachineConsts.EncryptionMachineEncryptSuccess;
            }
            catch (Exception ex)
            {
                result.Message = ServerConsts.ServerError;
                _logger.LogError(ex, EncryptionMachineConsts.EncryptionMachineEncryptError);
            }

            return result;
        }

        /// <summary>
        /// 对密文进行解密
        /// </summary>
        /// <param name="model">需要进行解密的数据</param>
        /// <returns>返回解密后的明文</returns>
        [HttpPost]
        public async Task<ActionResult<EncryptionMachineDecryptResult>> Decrypt(EncryptionMachineDencryptedModel model)
        {
            var result = new EncryptionMachineDecryptResult();

            try
            {
                var decryptedString = await _service.DecryptAsync(model);
                result.IsSuccess = true;
                result.DecryptedValue = decryptedString;
                result.Message = EncryptionMachineConsts.EncryptionMachineDecryptSuccess;
            }
            catch (FormatException)
            {
                result.Message = EncryptionMachineConsts.EncryptionMachineInvalidFormatError;
            }
            catch (Exception ex)
            {
                result.Message = ServerConsts.ServerError;
                _logger.LogError(ex, EncryptionMachineConsts.EncryptionMachineDecryptError);
            }

            return result;
        }
    }
}
